<template>
  <el-container>
    <el-aside width="350px">
      <el-tabs type="border-card">
        <el-tab-pane label="输入图层">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="srcRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('geojson_line')">移除</el-button>
          </div>
          <el-form :model="srcParameter" :rules="srcRules" ref="srcParameter">
            <el-form-item prop="srcTable" label="目标数据">
              <el-input  v-model="srcParameter.srcTable" autocomplete="off" placeholder="目标数据"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane> 
        <el-tab-pane label="样本点">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="sampleRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('geojson_point')">移除</el-button>
          </div>
          <el-form :model="sampleParameter" :rules="sampleRules" ref="sampleParameter">
            <el-form-item prop="newTable" label="样本数据">
              <el-input  v-model="sampleParameter.newTable" autocomplete="off" placeholder="样本数据"></el-input>
            </el-form-item>           
          </el-form>
        </el-tab-pane>  
        <el-tab-pane label="区域或网格">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="newRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('grid_line')">移除</el-button>
          </div>
          <el-form :model="newParameter" :rules="newRules" ref="newParameter">
            <el-form-item prop="newTable" label="目标数据">
              <el-input  v-model="newParameter.newTable" autocomplete="off" placeholder="目标数据"></el-input>
            </el-form-item>
            <el-form-item prop="radius" label="半径">
              <el-input  v-model="newParameter.radius" autocomplete="off" placeholder="半径"></el-input>
            </el-form-item>
            <el-form-item prop="gridType" label="网格类型">
              <el-input  v-model="newParameter.gridType" autocomplete="off" placeholder="网格类型(square,hexagon)"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>    
         

        <el-tab-pane label="网格取中心点">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="centerRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('center')">移除</el-button>
          </div>
          <el-form :model="centerParameter" :rules="centerRules" ref="centerParameter">
            <el-form-item prop="centerTable" label="网格数据">
              <el-input  v-model="centerParameter.centerTable" autocomplete="off" placeholder="网格数据"></el-input>
            </el-form-item>
            <el-form-item prop="radius" label="半径">
              <el-input  v-model="centerParameter.radius" autocomplete="off" placeholder="半径"></el-input>
            </el-form-item>
            <el-form-item prop="gridType" label="网格类型">
              <el-input  v-model="centerParameter.gridType" autocomplete="off" placeholder="网格类型(square,hexagon)"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane> 
            
        <el-tab-pane label="插值分析">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="interpolationRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('interpolation')">移除</el-button>
          </div>
          <el-form :model="interpolationParameter" :rules="rules" ref="interpolationParameter">
            <el-form-item prop="srcTable" label="原始数据">
              <el-input  v-model="interpolationParameter.srcTable" autocomplete="off" placeholder="输入原始数据"></el-input>
            </el-form-item>
            <el-form-item prop="sampleTable" label="样本数据">
              <el-input  v-model="interpolationParameter.sampleTable" autocomplete="off" placeholder="输入样本数据"></el-input>
            </el-form-item>
            <el-form-item prop="gridRadius" label="网格半径">
              <el-input  v-model="interpolationParameter.gridRadius" autocomplete="off" placeholder="输入网格半径"></el-input>
            </el-form-item>
            <el-form-item prop="weightField" label="权重字段">
              <el-input  v-model="interpolationParameter.weightField" autocomplete="off" placeholder="权重字段"></el-input>
            </el-form-item>
            <el-form-item prop="gridType" label="网格类型">
              <el-input  v-model="interpolationParameter.gridType" autocomplete="off" placeholder="网格类型" ></el-input>
            </el-form-item>                                
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-aside>
    <el-main>
      <div class="mapbox-maps">
        <div id="map">      
        </div> 
      </div>   
    </el-main>
  </el-container>  
</template>
<script>
export default{
    name:'PostgisInterpolationAnalysis',
    data(){
      return{
        oldGeosjon:'',
        geojsonPath: 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json',
        drawer: false,
        map:{},
        geojson: {        
          type:'geojson',
          data:{
          "type": "FeatureCollection",
          "features":[]
          }
        },
        jsonData: {},
        srcParameter:{
          srcTable:"hainan",//原始数据
        },
        sampleParameter:{
          newTable:"hainan_weather"
        },
        newParameter:{
          newTable:"hainan",
          radius:"0.1",
          gridType:"square"
        },
        centerParameter:{
          centerTable:"hainan",
          radius:"0.1",
          gridType:"square"
        },
        interpolationParameter:{
          srcTable:"hainan",
          sampleTable:"hainan_weather",
          gridRadius:0.1,
          weightField:"heat",
          gridType:"square"
        },
        srcRules: {
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ],                
        },
        sampleRules:{
           newTable: [
            { required: true, message: '请输入样本数据', trigger: 'blur' },
          ],  
        },
        newRules:{
          newTable: [
            { required: true, message: '请输入新数据', trigger: 'blur' },
          ],
          radius: [
            { required: true, message: '请输入半径', trigger: 'blur' },
          ],
          gridType: [
            { required: true, message: '请输入网格类型', trigger: 'blur' },
          ],
        },
        centerRules:{
          centerTable: [
            { required: true, message: '请输入新数据', trigger: 'blur' },
          ],
          radius: [
            { required: true, message: '请输入半径', trigger: 'blur' },
          ],
          gridType: [
            { required: true, message: '请输入网格类型', trigger: 'blur' },
          ],
        },
        rules: {
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ],
          sampleTable: [
            { required: true, message: '请输入样本数据', trigger: 'blur' },
          ],
          gridRadius: [
            { required: true, message: '请输网格半径', trigger: 'blur' },
          ],    
          weightField: [
            { required: true, message: '请输权重字段', trigger: 'blur' },
          ],  
          gridType: [
            { required: true, message: '请输网格类型', trigger: 'blur' },
          ],        
        },
      
      }
    },
    mounted() {
      this.loadMap()
    },
    beforeDestroy(){
      this.map.remove()

    },
    methods:{
        
      loadMap() {
        // 英文标注转换为中文   
        // mapboxgl.setRTLTextPlugin(
        //   "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js"
        // );
        this.map =  new mapboxgl.Map({
            accessToken: 'pk.eyJ1Ijoienh0d24iLCJhIjoiY2wzanV3bHduMTZwejNrcXcyd3B1bzBieiJ9.aW_TDqLomftwPvBu7OWqwQ',
            container: 'map',
            style: 'mapbox://styles/mapbox/outdoors-v10', // stylesheet location
            center: [110.47 ,  19.23],  //[116.79507,32.65542], // starting position [lng, lat]
            zoom: 8, // starting zoom
            hash: false,
            //pitch: 45,  //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
            bearing: 0, //地图的初始方向，值是北的逆时针度数，默认是0，即是正北
            antialias: true, //抗锯齿，通过false关闭提升性能
        })
        // 设置语言
        // var language = new MapboxLanguage({ defaultLanguage: "zh" });
        // this.map.addControl(language);

        //地图导航
        var nav = new mapboxgl.NavigationControl();
        this.map.addControl(nav, 'top-right');

        // 比例尺
        var scale = new mapboxgl.ScaleControl({
            maxWidth: 100,
            unit: "metric"
        });
        this.map.addControl(scale,"bottom-left");

        // 全图
        this.map.addControl(new mapboxgl.FullscreenControl());
        // 定位
        this.map.addControl(
            new mapboxgl.GeolocateControl({
            positionOptions: {
                enableHighAccuracy: true
            },
            trackUserLocation: true
            })
        );
        let that = this;
        this.map.on('load',function () {
          console.log(that)
          that.map.addSource("geojson_point",that.geojson);
          that.map.addSource("geojson_line",that.geojson);
          that.map.addSource("geojson_polygon",that.geojson);
          that.map.addSource("grid_line",that.geojson);
          that.map.addSource("interpolation",that.geojson);
          that.map.addSource("center",that.geojson);
          that.map.addLayer({			   
            "id": "geojson_polygon",
            "type": "fill",
            "source": "geojson_polygon",              
            "layout": {
              "visibility": "visible",			
            },
            "paint": {
              "fill-color":"#E43961",
              'fill-opacity': 1,
            }
          })
          that.map.addLayer({
            "id": "geojson_line",
            "type": "line",
            "source": "geojson_line",              
            "layout": {
              "visibility": "visible",			
            },
            "paint": {
              "line-opacity": 1,
              "line-color": "#000000",
              "line-width": 1,				
            }                 
          })  
          that.map.addLayer({
            "id": "geojson_text",
            "type": "symbol",
            "source": "geojson_polygon",              
            "layout": {
              "visibility": "visible",			
              'text-field': '{ct}',		
              'text-size': 12
            },
            paint: {
              'text-halo-color': '#0000FF',
              //'text-halo-width': 2
            }
          })             
          that.map.addLayer({
              id: "geojson_point",
              type: "circle",
              source: "geojson_point",
              paint: {
                  "circle-radius": 5,
                  "circle-color": "#00A54E",
              }
          }); 
          that.map.addLayer({
            "id": "geojson_grid_line",
            "type": "line",
            "source": "grid_line",              
            "layout": {
              "visibility": "visible",			
            },
            "paint": {
              "line-opacity": 1,
              "line-color": "#FBC003",
              "line-width": 1,				
            }                 
          })  
          that.map.addLayer({
              id: "interpolation_point",
              type: "circle",
              source: "interpolation",
              paint: {
                  "circle-radius": 3,
                  "circle-color": "#A20055",
              }
          }); 
          that.map.addLayer({
            "id": "interpolation_line",
            "type": "line",
            "source": "interpolation",              
            "layout": {
              "visibility": "visible",			
            },
            "paint": {
              "line-opacity": 1,
              "line-color": "#7700FF ",
              "line-width": 1,				
            }                 
          }) 	
          that.map.addLayer({
            "id": "interpolation_text",
            "type": "symbol",
            "source": "interpolation",              
            "layout": {
              "visibility": "visible",			
              'text-field': '{weigthfield}',		
              'text-size': 12
            },
            paint: {
              'text-halo-color': '#FF3333',
              //'text-halo-width': 2
            }
          })   	

          // that.map.addLayer({
          //   "id": "earthquakes-heat",
          //   "type": "heatmap",
          //   "source": "interpolation",
          //   "maxzoom": 16,
          //   "paint":{
          //     // 根据properties中的mag值来设置每一个点对热力图强度的贡献，mag在0-6,贡献从0-1
          //     "heatmap-weight": [
          //       "interpolate",
          //       ["linear"],
          //       ["get", "weigthfield"],
          //       15, 0,
          //       18, 1
          //     ],
          //       //根据zoom设置热力图强度变化
          //     "heatmap-intensity": [
          //       "interpolate",
          //       ["linear"],
          //       ["zoom"],
          //       0, 1,
          //       9, 9
          //     ],
          //     // 调整颜色
          //     "heatmap-color": [
          //       "interpolate",
          //       ["linear"],
          //       ["heatmap-density"],
          //       0, "rgba(0,0,0,0)",
          //       0.2, "rgba(25,70,150, .7)",
          //       0.4, "rgba(60,160,70, .7)",
          //       0.6, "rgba(250,230,30, .8)",
          //       0.8, "rgba(250,130,45, .9)",
          //       1, "rgba(255,36,36, .9)"
          //     ],
          //     // 根据zoom设置热力图计算半径
          //     "heatmap-radius": [
          //       "interpolate",
          //       ["linear"],
          //       ["zoom"],
          //       0, 2,
          //       9, 20
          //     ],
          //     // 根据zoom设置热力图透明度
          //     "heatmap-opacity": [
          //       "interpolate",
          //       ["linear"],
          //       ["zoom"],
          //       7, 1,
          //       9, 0
          //     ],
          //   }
          // })
          
          that.map.addLayer({
              id: "center_point",
              type: "circle",
              source: "center",
              paint: {
                  "circle-radius": 3,
                  "circle-color": "#FF0000",
              }
          });
            
        })          
      },  
      /**
      * 渲染geojson  line数据
      * 
      */
      srcRun(){
        let that = this
        that.$refs["srcParameter"].validate((valid) => {       
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.srcParameter.srcTable)                     
            let url = "/analysis/geojson"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.geom)    
                features.push({
                "type": "Feature",
                "geometry":geom,
                "properties": {"status": "status"}
                })	
              
              })
              that.map.getSource('geojson_line').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('geojson_line').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },	
      /**
      * 渲染geojson  point数据
      * 
      */
      sampleRun(){
        let that = this
        that.$refs["sampleParameter"].validate((valid) => {       
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.sampleParameter.newTable)                               
            let url = "/analysis/geojson"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.geom)    
                features.push({
                "type": "Feature",
                "geometry":geom,
                "properties": {"status": "status"}
                })	
              
              })
              that.map.getSource('geojson_point').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('geojson_point').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },	
      /**
      * 渲染网格数据
      * 
      */
      newRun(){
        let that = this
        that.$refs["newParameter"].validate((valid) => {       
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.newParameter.newTable)   
            fd.append("radius",that.newParameter.radius)
            fd.append("gridType",that.newParameter.gridType)                            
            let url = "/interpolation/grid"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.row_to_json.value)    
                features=geom.features              
              })
              that.map.getSource('grid_line').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('grid_line').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },	
      /**
       * 
       * 网格取中心点
       * 
       */
      centerRun(){
        let that = this
        that.$refs["centerParameter"].validate((valid) => {       
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("centerTable",that.centerParameter.centerTable)   
            fd.append("radius",that.centerParameter.radius)
            fd.append("gridType",that.centerParameter.gridType)                            
            let url = "/interpolation/center"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.row_to_json.value)    
                features=geom.features              
              })
              that.map.getSource('center').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('center').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                

      },
      /**
       * 
       * 开始分析
       * 
       */
      interpolationRun(){
          debugger
          let that = this
          that.$refs["interpolationParameter"].validate((valid) => {       
            if (valid) {          
              let fd =  new URLSearchParams()
              fd.append("srcTable",that.interpolationParameter.srcTable)   
              fd.append("sampleTable",that.interpolationParameter.sampleTable)
              fd.append("gridRadius",that.interpolationParameter.gridRadius)   
              fd.append("weightField",that.interpolationParameter.weightField) 
              fd.append("gridType",that.interpolationParameter.gridType)                          
              let url = "/interpolation/startAnalysis"
              that.$axios.post(url, fd)       
              .then(function (res) {          
                console.log(res)
                let features = []
                res.data.data.forEach(e=>{
                  console.log(e)
                  let geom = JSON.parse(e.geom)    
                  features.push(geom)			
                  features.push({
                    "type": "Feature",
                    "geometry":geom,
                    "properties": {"weigthfield": e.weigthfield}
                  })           
                 })
                that.map.getSource('interpolation').setData({
                    "type": "FeatureCollection",
                    "features":[]
                })
                that.map.getSource('interpolation').setData({
                    "type": "FeatureCollection",
                    "features":features
                })
              })
              .catch(function (error) {       
                console.log(error);
              })             
            } else {
              console.log('error submit!!');
              return false;
            }
          });           

      },
      remove(sourceId){
        let that = this
        that.map.getSource(sourceId).setData({
            "type": "FeatureCollection",
            "features":[]
        })

      },
   
    }
}

</script>
<style scoped lang="scss">
 @import "../../../public/mapbox/mapbox-gl.css";
 .mapbox-maps {
    width: 100%;
    height: calc(100vh - 50px);
    position: relative;
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        bottom:0;
        right: 0;        
    }
    
}
.mapboxgl-canvas {
    outline: none;
}
  /* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
    display: none;
} 
.el-aside {
    overflow: auto;
    box-sizing: border-box;
    flex-shrink: 0;
    width: 200px;
    // border: 1px solid red;
    line-height: 19px;
    padding: 10px;
    text-align: left;
}
.jv-container .jv-code.boxed {
    max-height: 100%;
}
</style>